import pandas as pd
from scipy.stats import chi2_contingency

data = pd.read_csv('../../data/raw/train.csv')
data['Age']=pd.cut(data['Age'],bins=[17,25,35,45,60],labels=[0,1,2,3])
data['DistanceFromHome']=pd.cut(data['DistanceFromHome'],bins=[0,3,5,10,15,20,30],labels=[0,1,2,3,4,5])
data['MonthlyIncome']=pd.cut(data['MonthlyIncome'],bins=[1000,2000,5000,8000,10000,15000,20000],labels=[0,1,2,3,4,5])
data['PercentSalaryHike']=pd.qcut(data['PercentSalaryHike'],3,labels=[0,1,2])
data['TotalWorkingYears']=pd.cut(data['TotalWorkingYears'],bins=[-1,1,2,5,10,20,30,40],labels=[0,1,2,3,4,5,6])
data['YearsAtCompany']=pd.cut(data['YearsAtCompany'],bins=[-1,1,2,5,10,20,30,40],labels=[0,1,2,3,4,5,6])
data['YearsInCurrentRole']=pd.cut(data['YearsInCurrentRole'],bins=[-1,1,2,5,10,18],labels=[0,1,2,3,4])
data['YearsSinceLastPromotion']=pd.cut(data['YearsSinceLastPromotion'],bins=[-1,1,2,5,10,18],labels=[0,1,2,3,5])
data['YearsWithCurrManager']=pd.cut(data['YearsWithCurrManager'],bins=[-1,1,3,5,8,12,17],labels=[0,1,2,3,4,5])

categorical_cols = data.iloc[:, 1:].columns.tolist()
# print("类别型特征：", categorical_cols)
target = 'Attrition'
chi2_results = []
for feature in categorical_cols:
    print(f"\n=== 卡方检验: {feature} vs {target} ===")

    # 构建列联表
    contingency = pd.crosstab(data[feature], data[target])

    # 执行卡方检验
    chi2, p, dof, expected = chi2_contingency(contingency)

    chi2_results.append({
        'Feature': feature,
        'Chi-square': chi2,
        'P-value': p,
        'DOF': dof,
        'Significant': p < 0.05
    })

    # 将结果转为 DataFrame 并按 p 值排序
pd.set_option('display.float_format', lambda x: '%.6f' % x)

# 输出排序后的结果

results_df = pd.DataFrame(chi2_results)
results_df = results_df.sort_values(by='P-value', ascending=True)

# 输出排序后的结果
print(results_df)
